package cn.com.inossem.activity;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.inossem.adapter.ApplyExpenseAdapter;
import cn.com.inossem.base.RequestActivity;
import cn.com.inossem.config.EventCode;
import cn.com.inossem.http.Api;
import cn.com.inossem.http.NetworkConnectGet;
import cn.com.inossem.http.NetworkConnectPost;
import cn.com.inossem.http.NetworkConnectPut;
import cn.com.inossem.model.EventBean;
import cn.com.inossem.model.ExpenseApplyBean;
import cn.com.inossem.utils.DialogUtil;
import cn.com.inossem.utils.TimeUtil;
import cn.com.inossem.utils.ToastUtil;
import cn.com.inossem.utils.Utils;

import static cn.com.inossem.activity.R.id.pro_hour_rv;

/**
 * 申请报销
 * Created by Mickey.Li on 2017-8-7.
 */
public class ProjectApplyExpenseActivity extends RequestActivity {
	private final static int RESULT_ADD_EXPENSE = 1;
	private static String incomeHtml = "报销总计:<font color='#FDB118'><big><big> 0 </big></big></font>元";
	@BindView(R.id.common_title)
	TextView commonTitle;
	@BindView(R.id.common_right_tv)
	TextView commonRightTv;
	@BindView(R.id.project_anticipated_income)
	TextView projectAnticipatedIncome;
	@BindView(R.id.project_apply_expense)
	TextView projectAddExpense;
	@BindView(R.id.project_apply_manHour)
	TextView projectApplyExpense;
	@BindView(R.id.pro_title)
	TextView proTitle;
	@BindView(R.id.pro_hour_order)
	TextView proExpenseOrder;
	@BindView(R.id.pro_hour_approver)
	TextView proExpenseApprover;
	@BindView(R.id.pro_hour_create)
	TextView proExpenseCreate;
	@BindView(R.id.apply_tab_1)
	TextView applyTab1;
	@BindView(R.id.apply_tab_2)
	TextView applyTab2;
	@BindView(R.id.apply_tab_3)
	TextView applyTab3;
	@BindView(pro_hour_rv)
	RecyclerView proExpenseRv;
	private boolean isEdit = false;
	private ExpenseApplyBean expenseBean;
	private ApplyExpenseAdapter mAdapter;
	private Intent mIntent;
	private String[] wbsStrs;
	private int orderStatus;
	private String orderId;
	private String serviceData;
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			try {
				dismissLoadPd();
				switch (msg.what) {
					case 1:
						ToastUtil.show(ProjectApplyExpenseActivity.this, "提交成功");
						EventBus.getDefault().post(new EventBean(EventCode.APPLY_EXPENSE_SUCC));
						finish();
						break;
					case 2:
						expenseBean = new GsonBuilder().setDateFormat("yyyy.MM.dd").create().fromJson(new JSONObject((String) msg.obj).getString("result"), new TypeToken<ExpenseApplyBean>() {
						}.getType());
						wbsStrs = expenseBean.projectInfoUser.getCostCode().split(",");
						for (ExpenseApplyBean.ExpenseItemBean itemBean : expenseBean.items) {
							itemBean.id = "";
						}
						if (orderStatus == 4) {
							serviceData = expenseBean.items2String();
						}
						initView();
						break;
					case 3:
						ToastUtil.show(ProjectApplyExpenseActivity.this, new JSONObject((String) msg.obj).getString("msg"));
						break;
					case 99:
						ToastUtil.show(ProjectApplyExpenseActivity.this, (String) msg.obj);
						break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};
	private PopupWindow savePopu;
	private View rootView;

	@Override
	public int getContentViewId() {
		return R.layout.act_project_apply_hour;
	}

	@Override
	public void initAllMembers(Bundle savedInstanceState) {
		super.initAllMembers(savedInstanceState);
		initData();
	}

	private void initData() {
		orderStatus = getIntent().getIntExtra("order_status", -1);
		switch (orderStatus) {
			case -1://申请
				wbsStrs = getIntent().getStringArrayExtra("expense_wbs");
				expenseBean = new ExpenseApplyBean();
				expenseBean.setProjectId(getIntent().getStringExtra("project_id"));
				expenseBean.no = getIntent().getStringExtra("expense_id");
				expenseBean.approveMail = getIntent().getStringExtra("project_approver");
				expenseBean.project.projectName = getIntent().getStringExtra("project_name");
				expenseBean.createDate = new Date();
				expenseBean.projectInfoUser.setRealProjectName("");
				initView();
				return;
			case 0://审批中
			case 1://已通过
			case 3://已结算
				findViewById(R.id.project_detail_bottom2).setVisibility(View.GONE);
				break;
			case 2://未通过
			case 4://暂存
				break;
		}
		orderId = getIntent().getStringExtra("order_id");
		requestApplyedExpense();
	}

	private void initView() {
		commonTitle.setText(getString(R.string.expense_apply_title));
		findViewById(R.id.common_right_img).setVisibility(View.GONE);
		if (orderStatus == -1 || orderStatus == 2 || orderStatus == 4) {
			commonRightTv.setVisibility(View.VISIBLE);
			commonRightTv.setText(getString(R.string.expense_apply_titleR));
		} else if (orderStatus == 0) {
			commonRightTv.setVisibility(View.VISIBLE);
			commonRightTv.setText(getString(R.string.expense_apply_titleR2));
		}
		if (TextUtils.isEmpty(expenseBean.projectInfoUser.getRealProjectName())) {
			proTitle.setText(expenseBean.project.projectName);
		} else {
			proTitle.setText(expenseBean.projectInfoUser.getRealProjectName());
		}
		proExpenseOrder.setText(getString(R.string.expense_no) + " " + expenseBean.no);
		proExpenseApprover.setText(getString(R.string.project_approver) + " " + expenseBean.approveMail);
		proExpenseCreate.setText(getString(R.string.expense_create) + " " + TimeUtil.getDay(expenseBean.createDate));
		findViewById(R.id.pro_hour_wbs).setVisibility(View.GONE);
		findViewById(R.id.pro_hour_contract_num).setVisibility(View.GONE);
		applyTab1.setText(getString(R.string.expense_apply_tab1));
		applyTab2.setText(getString(R.string.expense_wbs));
		applyTab3.setText(getString(R.string.expense_apply_tab3));
		findViewById(R.id.project_manHour_total).setVisibility(View.GONE);
		findViewById(R.id.pro_money_divider).setVisibility(View.INVISIBLE);
		projectAnticipatedIncome.setText(Html.fromHtml(incomeHtml));
		projectAnticipatedIncome.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
		projectAnticipatedIncome.setPadding(50, 0, 50, 0);
		projectAddExpense.setText(getString(R.string.expense_add));
		projectApplyExpense.setText(getString(R.string.expense_apply_submit));
		proExpenseRv.setLayoutManager(new LinearLayoutManager(this));
		proExpenseRv.setAdapter(mAdapter = new ApplyExpenseAdapter(this, this, orderStatus));
		mAdapter.setExpenseList(expenseBean.items);
		notifyExpenseMoney();
	}

	@OnClick({R.id.common_back, R.id.common_right_tv, R.id.project_apply_expense, R.id.project_apply_manHour})
	public void onViewClicked(View view) {
		switch (view.getId()) {
			case R.id.common_back:
				if (!judgeExpList()) {
					finish();
				}
				break;
			case R.id.common_right_tv:
				if (orderStatus == -1 || orderStatus == 2 || orderStatus == 4) {
					isEdit = !isEdit;
					commonRightTv.setText(isEdit ? getString(R.string.dialog_cancle) : getString(R.string.expense_apply_titleR));
					projectAddExpense.setText(isEdit ? getString(R.string.expense_del) : getString(R.string.expense_add));
					projectApplyExpense.setText(isEdit ? getString(R.string.dialog_cancle) : getString(R.string.expense_apply_submit));
					mAdapter.changeEditStatus(isEdit);
					return;
				}
				showEmailDialog();
				break;
			case R.id.project_apply_expense:
				if (isEdit) {
					//删除报销
					if (expenseBean.items.size() < 1) {
						ToastUtil.show(this, getString(R.string.expense_apply_null));
					} else {
						for (int i = mAdapter.getItemCount(); i >= 0; i--) {
							if (mAdapter.selArray.get(i)) {
								expenseBean.items.remove(i);
							}
						}
						mAdapter.setExpenseList(expenseBean.items);
						notifyExpenseMoney();
					}
				} else {
					//添加报销
					mIntent = new Intent(this, ProjectAddExpenseActivity.class);
					mIntent.putExtra("project_id", expenseBean.project.id);
					mIntent.putExtra("project_wbs", wbsStrs);
					startActivityForResult(mIntent, RESULT_ADD_EXPENSE);
				}
				break;
			case R.id.project_apply_manHour:
				if (isEdit) {
					onViewClicked(commonRightTv);
				} else {
					if (expenseBean.items.size() > 0) {
						if (TextUtils.isEmpty(Utils.messageInfo.userInfo.getBankType()) || TextUtils.isEmpty(Utils.messageInfo.userInfo.getBankAccount())) {
							DialogUtil.getInstance(ProjectApplyExpenseActivity.this).showDialog(getString(R.string.notice_bank_null), 0, null, DialogUtil.DialogType.PROMPT, 0, new DialogUtil.DialogCallBack() {
								@Override
								public void back(int tag, String content, int which) {
									if (which == -1) {
										mIntent = new Intent(ProjectApplyExpenseActivity.this, MyInformationActivity.class);
										startActivity(mIntent);
									}
								}
							});
						} else {
							expenseBean.status = 0;
							requestApplyExpense();
						}
					} else {
						ToastUtil.show(this, getString(R.string.expense_apply_null));
					}
				}
				break;
		}
	}

	private boolean expenseListIsNull() {
		return expenseBean.items.size() == 0;
	}

	private void showSavePopu() {
		setScreenBritness(5);
		if (null == savePopu) {
			rootView = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
			View popuView = LayoutInflater.from(this).inflate(R.layout.layout_save_popu, null);
			popuView.findViewById(R.id.popu_exp_save).setOnClickListener(this);
			popuView.findViewById(R.id.popu_exp_continue).setOnClickListener(this);
			popuView.findViewById(R.id.popu_exp_close).setOnClickListener(this);
			savePopu = new PopupWindow(popuView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
			savePopu.setAnimationStyle(R.style.popwin_anim_style);
			savePopu.setBackgroundDrawable(new BitmapDrawable());
			savePopu.setOutsideTouchable(false);
			savePopu.setOnDismissListener(new PopupWindow.OnDismissListener() {
				@Override
				public void onDismiss() {
					setScreenBritness(10);
				}
			});
		}
		savePopu.showAtLocation(rootView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
	}

	/**
	 * 设置屏幕亮度
	 *
	 * @param brightness 亮度值
	 */
	private void setScreenBritness(int brightness) {
		//设置当前activity的屏幕亮度
		WindowManager.LayoutParams lp = this.getWindow().getAttributes();
		//0到1,调整亮度暗到全亮
		lp.alpha = Float.valueOf(brightness / 10f);
		this.getWindow().setAttributes(lp);
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
			case R.id.item_hour_num:
				DialogUtil.getInstance(this).showDialog(getString(R.string.expense_money_notice), (int) v.getTag(), null, DialogUtil.DialogType.NUMBER, 0, new DialogUtil.DialogCallBack() {
					@Override
					public void back(int tag, String content, int which) {
						expenseBean.items.get(tag).amount = Double.parseDouble(content);
						mAdapter.changeExpenseItem(tag, Double.parseDouble(content));
						notifyExpenseMoney();
					}
				});
				break;
			case R.id.popu_exp_save:
				savePopu.dismiss();
				expenseBean.status = 4;
				requestApplyExpense();
				break;
			case R.id.popu_exp_continue:
				savePopu.dismiss();
				break;
			case R.id.popu_exp_close:
				savePopu.dismiss();
				finish();
				break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			if (requestCode == RESULT_ADD_EXPENSE) {
				final ExpenseApplyBean.ExpenseItemBean itemBean = data.getParcelableExtra("expenseItem");
				expenseBean.items.add(itemBean);
				mAdapter.addExpenseItem(itemBean);
				notifyExpenseMoney();
			}
		}
	}

	private void requestApplyExpense() {
		showLoadPd();
		if (orderStatus == -1 || orderStatus == 4) {
			new NetworkConnectPost(this, Api.PROJECT_APPLY_EXPENSE, mHandler, 1, ExpenseApplyBean.expense2Json(expenseBean));
		} else if (orderStatus == 2) {
			new NetworkConnectPut(this, Api.PROJECT_APPLY_EXPENSE + "/" + expenseBean.id, mHandler, 1, ExpenseApplyBean.expense2Json(expenseBean));
		}
	}

	private void requestApplyedExpense() {
		showLoadPd();
		new NetworkConnectGet(this, Api.PROJECT_APPLYED_EXPENSE + orderId, mHandler, 2);
	}

	/**
	 * 报销催办邮件
	 */
	private void requestExpenseEmail() {
		showLoadPd();
		new NetworkConnectGet(this, Api.EXPENSE_EMAIL + orderId, mHandler, 3);
	}

	private void notifyExpenseMoney() {
		if (orderStatus == -1 || orderStatus == 2 || orderStatus == 4) {
			expenseBean.sum = 0;
			if (expenseBean.items.size() > 0) {
				for (int i = 0; i < expenseBean.items.size(); i++) {
					expenseBean.sum += expenseBean.items.get(i).amount;
				}
			}
		}
		projectAnticipatedIncome.setText(Html.fromHtml(incomeHtml.replace("0", "" + expenseBean.sum)));
	}

	private void showEmailDialog() {
		DialogUtil.getInstance(ProjectApplyExpenseActivity.this).showDialog(getString(R.string.te_email_content), 0, null, DialogUtil.DialogType.PROMPT, 0, new DialogUtil.DialogCallBack() {
			@Override
			public void back(int tag, String content, int which) {
				if (which == -1) {
					requestExpenseEmail();
				}
			}
		});
	}

	@Override
	public void onBackPressed() {
		if (!judgeExpList()) {
			finish();
		}
	}

	private boolean judgeExpList() {
		if ((orderStatus == -1 && !expenseListIsNull()) || (orderStatus == 4 && !serviceData.equals(expenseBean.items2String()))) {
			showSavePopu();
			return true;
		}
		return false;
	}
}
